import 'package:easy_read_comic/controller/comic/read_controller.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:screen_brightness/screen_brightness.dart';

class ChapterBrightnessWidget extends StatefulWidget {
  final ReadController readController;

  ChapterBrightnessWidget(this.readController);

  @override
  State<StatefulWidget> createState() => _chapterBrightnessWidget();
}

class _chapterBrightnessWidget extends State<ChapterBrightnessWidget> {
  double _currentSliderValue = 100.0;

  @override
  void initState() {
    super.initState();
    this.getScreenBrightness();
  }

  @override
  Widget build(BuildContext context) {
    return DraggableScrollableSheet(
      initialChildSize: 0.15,
      minChildSize: 0.15,
      maxChildSize: 0.3,
      expand: false,
      builder: (BuildContext context, ScrollController scrollController) {
        return Container(
          padding: EdgeInsets.only(
            left: 10,
            right: 10,
            bottom: 10,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '亮度: ${_currentSliderValue.round()}%',
                style: TextStyle(
                  fontSize: 18,
                ),
              ),
              Slider(
                value: _currentSliderValue,
                min: 0,
                max: 100,
                label: _currentSliderValue.toString(),
                onChanged: (double value) {
                  this.setScreenBrightness(value);
                  setState(() {
                    _currentSliderValue = value;
                  });
                },
              ),
            ],
          ),
        );
      },
    );
  }

  void getScreenBrightness() async {
    try {
      _currentSliderValue = (await ScreenBrightness().current * 100);
      setState(() {});
    } catch (e) {
      Logger().e("获取屏幕亮度失败:${e.toString()}");
    }
  }

  void setScreenBrightness(double brightness) async {
    try {
      await ScreenBrightness().setScreenBrightness(brightness / 100);
    } catch (e) {
      Logger().e("设置屏幕亮度失败:${e.toString()}");
    }
  }
}
